package org.xmx0632.connector.protocol.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.model.Gateway;
import org.xmx0632.connector.protocol.message.Response;
import org.xmx0632.connector.protocol.message.TerminatorsControl1001DownRequest;
import org.xmx0632.connector.util.GlobalGateway;

/**
 * 5.4 控制指令下发流程
 * 
 *
 */
@Component
public class TerminatorsControl1001DownRequestProcessor
		extends BaseMessageProcessor<TerminatorsControl1001DownRequest, Response> {

	public static final Logger LOG = LoggerFactory.getLogger(TerminatorsControl1001DownRequestProcessor.class);

	@Override
	public Response process(TerminatorsControl1001DownRequest message) {
		try {
			LOG.debug("process message:{}", message);
			// TODO 接收下发指令后,更新数据库中的下发消息,清理内存中指令信息
			LOG.debug("接收下发指令后,更新数据库中的下发消息(可以考虑异步实现),清理内存中指令信息");
			if (message.getGateway() == null) {
				LOG.error("invalid request");
				return Response.NO_RESPONSE;
			}
			String gatewayId = message.getGateway().getGatewayId();
			LOG.debug("gatewayId:{}", gatewayId);
			Gateway gateway = GlobalGateway.get(gatewayId);
			LOG.debug("gateway:{}", gateway);
			if (gateway == null) {
				LOG.error("gateway:{} not connected,skip the request.", gatewayId);
				return Response.NO_RESPONSE;
			}
			gateway.getChannel().writeAndFlush(message);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

		// 不返回响应消息
		return Response.NO_RESPONSE;
	}
}
